package bfw3b9.atprin.project;

import android.graphics.Canvas;
import android.view.SurfaceHolder;


/**
 * @author Tobias Sommer
 *
 * Der Thread, der die Berechnungen ausfuehrt.
 */
public class DrawThread extends Thread  {
  
	private SurfaceHolder surfaceHolderFront;
	private MotionPathView frontView;
	private GameController context;
	private boolean isRunning;
	private long nextTimeStamp;
	private int delay;
	private long newSpawn;
	private boolean notLastCreep;


	/**
	 * @author Tobias Sommer
	 * 
	 * Konstruktor der die Activity und den View uebergibt.
	 * 
	 * @param surfaceHolderFront, Surface Holder
	 * @param view, View auf dem das Canvas liegt
	 * @param con, Activity
	 */
	public DrawThread(SurfaceHolder surfaceHolderFront, MotionPathView view, GameController con){
		
		//Der Delay zwingt den Thread auf eine FPS von 1000/25 (=40)
		this.delay = 25;
				
	    this.nextTimeStamp = 0;
	    this.surfaceHolderFront = surfaceHolderFront;
	    this.frontView = view;
	    this.isRunning = true;
	    this.newSpawn = 0;
	    this.context = con;
	    this.notLastCreep = true;   

	    
    }
	
	/**
	 * @author Tobias Sommer
	 * 
	 * Durchlaeuft die Berechnungen wenn der Thread aktiv ist.
	 */
	@Override
	public void run(){
		
		Canvas cFront;
		
		//Wenn Thread aktiv
		while (this.isRunning){
			
			if (GameController.getGameStatus() != GameController.RUNNING){
				//Wenn das Spiel nicht laeuft tue nichts
			}else{
				cFront = null;

				try{
					//Sleep bis der naechste Schritt durchgefuehrt werden soll
					if (this.nextTimeStamp > System.currentTimeMillis()){
						try{
							sleep(this.nextTimeStamp - (System.currentTimeMillis()));
						} catch (InterruptedException ignore){
	           
						}
					}
					
					//Spawner fuer die Creeps
					if (this.newSpawn <= System.currentTimeMillis() && this.notLastCreep){
						this.notLastCreep = this.context.spawn();
						this.newSpawn = (long) (System.currentTimeMillis() + Math.random()*2000) + 1500;
					}
					
					//Schuesse durchfuehren
					this.context.shootAll();
					
					//neuer Frame
					this.context.newFrame();
					
					//Nachster Frame in 25ms
					this.nextTimeStamp = System.currentTimeMillis() + this.delay;
	       
					cFront = this.surfaceHolderFront.lockCanvas(null);
					synchronized (this.surfaceHolderFront){
						this.frontView.onDraw(cFront);
					}
				} finally{
					if (cFront != null){
						this.surfaceHolderFront.unlockCanvasAndPost(cFront);
					}
				}
			}
		}
	}
	
	//Es folgen Setter
	
	public void setRunning(boolean _isRunning){
		
		this.isRunning = _isRunning;
	}
	
	public void setNotLastCreep(boolean _notlastCreep){
		this.notLastCreep = _notlastCreep;
	}
}
